import { conversionChartsData, reservedBits } from '@/src/utils/commonFunc';
import dictionaryConfig from '@/src/utils/dictionaryConfig';
import { useExportMoreTableInSheet } from '@/src/utils/exportExcelHooks';
import { AdvancedSearch, DATA_ENTRY, ContentPackage, ProductListC, PrimaryGhostC, XYAxisChartsC, FirstHeaderC } from '@/comps/index';
import React, { useRef, useEffect, useState } from 'react';
import moment from 'moment';
import { times } from 'number-precision';
import { cloneDeep } from 'lodash';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import styles from './index.less';
import TitleTableC from './TitleTable';
import { Spin, message } from 'antd';
import { namespace } from '@/src/newModels/leverageAnalysis/PortfolioManageLeverageAnalysisM';
import { connect } from 'dva';
import LabelSettingsModal from './LabelSettingsModal';
import colors from '@/css/colors';
// 查询id， 查询列表id，产品下拉id

let timerForQuery, timerForData, timerForProduct;
const LeverageAnalysis = (props) => {
  const { form, dispatch } = props;
  const dateRef = useRef(); // 日期范围ref
  const productListRef = useRef(); // 产品下拉ref
  const tableRef1 = useRef(null); // table ref
  const tableRef2 = useRef(null); // table ref
  const tableRef3 = useRef(null); // table ref
  const [tradingDate, setTradingDate] = useState();
  const [defaultSelect, setDefaultSelect] = useState(); // 默认选中的行-productValue
  const [currentProductInfo, setCurrentProductInfo] = useState(null);
  const [spinning, setSpinning] = useState(false); // echarts loading
  const [pageSpinning, setPageSpinning] = useState(false); // 页面 loading
  const [labelSetVisible, setLabelSetVisible] = useState(false); // 标签设置
  const [cordonValue, setCordonValue] = useState(0); // 警戒线值
  const [dateRange, setDateRange] = useState({
    startDate: undefined,
    endDate: undefined,
  }); // 时间区间
  const [series, setSeries] = useState([]);
  const [xAxis, setXAxis] = useState([]);
  const [exportData, setExportData] = useState([]); // 导出数据
  const [isMarkPoint, setIsMarkPoint] = useState(true); // 是否显示最大最小值
  // 初始化查询栏数据
  const initQuery = (previousDate) => {
    timerForQuery = setInterval(() => {
      if (dateRef.current.state.SelectC) {
        clearInterval(timerForQuery);
        dateRef.current.setSelctAndDate('5', moment().subtract(3, 'M').add(0, 'd'), moment(previousDate));
        setDateRange({
          ...dateRange,
          endDate: previousDate || moment().format('YYYY-MM-DD'),
          startDate: moment().subtract(3, 'M').add(0, 'd').format('YYYY-MM-DD'),
        });
      }
    }, 100);
  };
  // 产品下拉
  const getProductList = (callback) => {
    setPageSpinning(true);
    timerForProduct = setInterval(() => {
      if (productListRef.current?.state?.fullProducts?.length > 0) {
        clearInterval(timerForProduct);
        callback(productListRef.current.state.fullProducts);
      }
    }, 100);
  };
  // table下拉
  const initDefaultSelected = (fullProducts) => {
    timerForData = setInterval(() => {
      const data1 = tableRef1.current.getDataSource(); // 现金管理类数据
      // data1.length > 0 用于判断产品初始化选中时候已经获取到了产品 所以接口返回为空数组时，应该处理成[null],
      if (tableRef1.current && data1.length > 0) {
        clearInterval(timerForData);
        setDefaultSelect(data1[0]?.productValue); // 设置默认选中现金管理类第一个
        productListRef.current.setSelect(data1[0]?.productValue ?? fullProducts[0].value); // 设置选中产品,如果现金管理类没返回那么选中产品第一个
        if (data1[0]?.length === 0 || data1[0] === null) {
          setCurrentProductInfo(null);
        } else {
          setCurrentProductInfo({
            // 设置选中产品的参数
            portfolioCode: data1[0]?.productCode,
            title: `${data1[0]?.productCode}-${data1[0]?.productName}`, // 导出用
          });
        }
        setPageSpinning(false);
      }
    }, 100);
  };
  const getTradingDate = () => {
    dispatch({
      type: `globalM/getTradingDate`,
      payload: { type: '2' },
      callback: (res) => {
        setTradingDate(moment(res).format('YYYY-MM-DD')); // Previous前交易日
        initQuery(moment(res).format('YYYY-MM-DD')); // 初始化查询栏数据
      },
    });
  };
  useEffect(() => {
    getTradingDate();
    getProductList(initDefaultSelected);
    return () => {
      clearInterval(timerForData);
      clearInterval(timerForQuery);
    };
  }, []);
  const handleSearch = (e) => {
    if (!e) {
      initQuery(tradingDate);
      setDateRange({
        ...dateRange,
        endDate: tradingDate || moment().format('YYYY-MM-DD'),
        startDate: moment().subtract(3, 'M').add(0, 'd').format('YYYY-MM-DD'),
      });
      tableRef1.current?.reset();
      tableRef2.current?.reset();
      tableRef3.current?.reset();
      return;
    }
    setDateRange({
      ...dateRange,
      startDate: e.startDate.format('YYYY-MM-DD'),
      endDate: e.endDate.format('YYYY-MM-DD'),
    });
  };

  // 获取杠杆率趋势图
  const getLeverageTrendChart = () => {
    setSpinning(true);
    const productObj = {
      productCode: currentProductInfo?.portfolioCode,
    };
    dispatch({
      type: `${namespace}/queryLeverageTrendChart`,
      payload: {
        ...dateRange,
        ...productObj,
      },
      callback: (data) => {
        const [xAxisData, seriesData] = conversionChartsData(data);
        const copySeriesData = cloneDeep(seriesData);
        copySeriesData.map((v) => {
          v.data = v.data.map((item) => (item ? times(item, 100) : item));
        });
        setExportData(data[0]?.data);
        setXAxis(xAxisData);
        const elementsAreEqual = copySeriesData[0].data.every((el) => el === copySeriesData[0]?.data[0]);
        if (elementsAreEqual) setIsMarkPoint(false);
        else setIsMarkPoint(true); // 如果是直线则不显示最大最小值
        setSeries([...copySeriesData]);
        setCordonValue(data[0]?.cordonValue ? times(data[0]?.cordonValue, 100) : 0);
        setSpinning(false);
      },
    });
  };
  useEffect(() => {
    if (dateRange.endDate && dateRange.startDate && currentProductInfo) getLeverageTrendChart();
  }, [dateRange.endDate, dateRange.startDate, currentProductInfo]);

  const exportXlsxFile = () => {
    if (!currentProductInfo) return message.warning('请选择产品');
    const groupedHeader = [['日期', '杠杆率（%）']];
    const res = [];
    for (const key in exportData[0]) {
      if (exportData[0][key]) {
        res.push([key, exportData[0][key] ? times(exportData[0][key], 100) : '']);
      }
    }
    const sheetConfig = {
      sheet1: {
        sheetBody: [
          {
            type: 3,
            anyXlsxData: [...groupedHeader, ...res],
          },
        ],
      },
    };
    // eslint-disable-next-line react-hooks/rules-of-hooks
    useExportMoreTableInSheet(sheetConfig, currentProductInfo?.title);
  };
  const searchProps = {
    dataSource: [
      {
        previousDateType: 2,
        selectIndex: 'complextdate1',
        startIndex: 'startDate',
        endIndex: 'endDate',
        hasDataED: moment(tradingDate),
        type: DATA_ENTRY.COMPLEXDATE,
        selfDefination: ['0', '4', '5', '6', '7'],
        initialValue: '2',
        onRef: (ref) => (dateRef.current = ref),
      },
    ],
    onQuery: handleSearch,
    onClear: handleSearch,
  };
  const handleSelectProduct = (productInfo) => {
    console.log(productInfo);
    setCurrentProductInfo(productInfo?.info ?? null);
    if (productInfo) setDefaultSelect(productInfo?.info?.value);
  };

  const { cashManage, openPublicOffering, closedAndOthers } = dictionaryConfig.leverageUpperLimit;
  const columns = [
    { key: 'productName', title: '产品名称', width: 210, align: 'left', render: (_, record) => (_ ? `${record.productCode}-${record.productName}` : '--') },
    {
      key: 'maxLeverage',
      title: '最高杠杆率（%）',
      width: 120,
      align: 'right',
      className: 'maat-column-cell',
      onCell: (record) => {
        const text = record.maxLeverage;
        const limitValue = record.productType == 1 ? cashManage : record.productType == 2 ? openPublicOffering : record.productType == 3 ? closedAndOthers : 0;
        const cellProps = {};
        cellProps.style = {
          background: Number(times(text ?? 0, 100)) > Number(limitValue) ? '#FDECEB' : 'unset',
        };
        return cellProps;
      },
      render: (text) => {
        if (!text && text !== 0) return '--';
        return <div>{reservedBits(Number.parseFloat(times(text, 100)))}</div>;
      },
    },
    {
      key: 'maxLeverageDate',
      title: '日期',
      width: 80,
      align: 'left',
      render: (text) => {
        if (!text && text !== 0) return '--';
        return moment(text).format('YYYY-MM-DD');
      },
    },
    {
      key: 'minLeverage',
      title: '最低杠杆率（%）',
      width: 120,
      align: 'right',
      render: (text) => {
        if (!text && text !== 0) return '--';
        return reservedBits(Number.parseFloat(times(text, 100)));
      },
    },
    {
      key: 'minLeverageDate',
      title: '日期',
      width: 80,
      align: 'left',
      render: (text) => {
        if (!text && text !== 0) return '--';
        return moment(text).format('YYYY-MM-DD');
      },
    },
    {
      key: 'averageLeverage',
      title: '平均杠杆率（%）',
      width: 120,
      align: 'right',
      render: (text) => {
        if (!text && text !== 0) return '--';
        return reservedBits(Number.parseFloat(times(text, 100)));
      },
    },
    {
      key: 'differenceLever',
      title: '杠杆率差（%）',
      width: 100,
      align: 'right',
      render: (text) => {
        if (!text && text !== 0) return '--';
        return reservedBits(Number.parseFloat(times(text, 100)));
      },
    },
  ];
  const minY =
    series.length > 0 && (Math.min(...series[0].data?.filter((v) => v !== null)) > 90 ? 90 : Math.floor(Math.min(...series[0].data.filter((v) => v !== null)) / 10) * 10);
  return (
    <ContentPackage
      title='杠杆率分析'
      contentHtml={
        <Spin wrapperClassName={styles.LeverageAnalysis} spinning={pageSpinning}>
          <AdvancedSearch {...searchProps} />
          <div style={{ margin: '20px 0' }}>
            <FirstHeaderC title='杠杆率趋势图' />
          </div>
          {/* 操作栏 */}
          <div className={styles.operate}>
            <div>
              <ProductListC
                isExistence={true}
                dataType={2}
                allowClear={false}
                title={'产品名称'}
                formItemLayout={{
                  labelCol: { span: 4 },
                  wrapperCol: { span: 12 },
                }}
                positionBody={true}
                form={form}
                dataIndex='productdataIndex'
                initialValue={undefined}
                onRef={(ref) => (productListRef.current = ref)}
                onChange={(e) => handleSelectProduct(e)}
              />
            </div>
            <div>
              <PrimaryGhostC disabled={!currentProductInfo || series[0]?.data?.length === 0} title={'导出'} onClick={exportXlsxFile} />
            </div>
          </div>
          {/* echarts */}
          <Spin spinning={spinning}>
            <XYAxisChartsC
              yAxisRange={[[minY]]}
              isMarkPoint={isMarkPoint}
              series={series}
              xAxis={xAxis}
              yAxisUnit={['杠杆率（%）']}
              height={400}
              type='line'
              dataZoom={true}
              cordonConfig={{
                cordonValue,
              }}
            />
          </Spin>
          {/* 杠杆率明细结果表 */}
          <div className={styles.LabelSettings}>
            <div>
              <FirstHeaderC title='杠杆率明细结果表' />
            </div>
            <div>
              <PrimaryGhostC title={'标签设置'} onClick={() => setLabelSetVisible(true)} />
            </div>
          </div>
          <div className={styles.allTables}>
            <TitleTableC
              ref={tableRef1}
              onClickRow={(record) => {
                setDefaultSelect(record.productValue);
                productListRef.current.setSelect(record?.productValue); // 设置选中产品
              }}
              setRowClass={(record) => {
                return defaultSelect === record?.productValue ? 'selectInTable' : '';
              }}
              dateRange={dateRange}
              columns={columns}
              effect={`${namespace}/queryLeverageDetailResults`}
              payloadType={{ productType: 1 }}
              title={`现金管理类：上限${cashManage}%`}
              sorterKeys={['maxLeverage', 'minLeverage', 'averageLeverage', 'differenceLever']}
            />
            <TitleTableC
              ref={tableRef2}
              onClickRow={(record) => {
                setDefaultSelect(record.productValue);
                productListRef.current.setSelect(record?.productValue); // 设置选中产品
              }}
              setRowClass={(record) => {
                return defaultSelect === record?.productValue ? 'selectInTable' : '';
              }}
              dateRange={dateRange}
              columns={columns}
              effect={`${namespace}/queryLeverageDetailResults`}
              payloadType={{ productType: 2 }}
              title={`开放式公募：上限${openPublicOffering}%`}
              sorterKeys={['maxLeverage', 'minLeverage', 'averageLeverage', 'differenceLever']}
            />
            <TitleTableC
              ref={tableRef3}
              onClickRow={(record) => {
                setDefaultSelect(record.productValue);
                productListRef.current.setSelect(record?.productValue); // 设置选中产品
              }}
              setRowClass={(record) => {
                return defaultSelect === record?.productValue ? 'selectInTable' : '';
              }}
              dateRange={dateRange}
              columns={columns}
              effect={`${namespace}/queryLeverageDetailResults`}
              payloadType={{ productType: 3 }}
              title={`封闭式及其他：上限${closedAndOthers}%`}
              sorterKeys={['maxLeverage', 'minLeverage', 'averageLeverage', 'differenceLever']}
            />
          </div>
          {labelSetVisible && <LabelSettingsModal visible={labelSetVisible} operate={(operateType) => setLabelSetVisible(operateType)} />}
        </Spin>
      }
    />
  );
};
const LeverageAnalysisForm = Form.create()(LeverageAnalysis);
const mapState = ({ loading, globalM }) => ({ loading, globalM });
export default connect(mapState)(LeverageAnalysisForm);
